package com.gancp.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gancp.controller.base.BaseController;
import com.gancp.entity.UserInfo;
import com.gancp.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by GCP on 2018/7/5.
 */
@Controller
@RequestMapping("demo")
public class Demo extends BaseController{

    @Autowired
    private UserInfoService userInfoService;

    @Value(value = "${config.myName}")
    private String myName;

    @RequestMapping("/say")
    @ResponseBody
    public String saveHello() throws Exception {
        if (true){
            throw new Exception( "exception" );
        }
        return "hello:" + myName;
    }


    @RequestMapping("/user")
    @ResponseBody
    public UserInfo userInfo() {
        return userInfoService.selectByPrimaryKey( "1" );
    }

    @RequestMapping("/json")
    @ResponseBody
    public String fastJsonTest() {
        Map<String, Object> map = new HashMap<>();
        map.put( "a", null );
        map.put( "b", "b" );
        map.put( "c", new HashMap<String, Object>() );
        map.put( null, "d" );
        map.put( "e", "" );
        // 不输出null值的写法
        // String str = JSONObject.toJSONString( map );
        // 结果{null:"d","b":"b","c":{},"e":""}  键值为空可以输出，但是value是null不会输出
        // 使用输出null值的序列化方法
        String str = JSONObject.toJSONString( map, SerializerFeature.WriteMapNullValue );
        // 结果 {null:"d","a":null,"b":"b","c":{},"e":""}
        return str;
    }
}
